const mysql = require('mysql2/promise');
const fs = require('fs').promises;
const path = require('path');
require('dotenv').config();

async function initDatabase() {
  let connection;
  try {
    // 创建数据库连接
    connection = await mysql.createConnection({
      host: process.env.DB_HOST || 'localhost',
      user: process.env.DB_USER || 'root',
      password: process.env.DB_PASSWORD || '',
      multipleStatements: true
    });

    console.log('数据库连接成功');

    // 读取SQL文件
    const sqlFile = await fs.readFile(path.join(__dirname, '..', 'database.sql'), 'utf8');
    
    // 执行SQL文件
    await connection.query(sqlFile);
    
    console.log('数据库初始化成功');

    // 创建超级管理员账号
    const adminData = {
      phone: '13800138000',
      name: '超级管理员',
      nickname: '系统管理员',
      role: 'super',
      gas_card_balance: 0.00
    };

    // 检查是否已存在超级管理员
    const [admins] = await connection.execute(
      'SELECT id FROM bangninsheng.users WHERE role = "super"'
    );

    if (admins.length === 0) {
      await connection.execute(
        'INSERT INTO bangninsheng.users (phone, name, nickname, role, gas_card_balance) VALUES (?, ?, ?, ?, ?)',
        [adminData.phone, adminData.name, adminData.nickname, adminData.role, adminData.gas_card_balance]
      );
      console.log('超级管理员账号创建成功:', adminData);
    } else {
      console.log('超级管理员账号已存在');
    }

  } catch (error) {
    console.error('初始化失败:', error);
  } finally {
    if (connection) {
      await connection.end();
    }
    process.exit();
  }
}

initDatabase(); 